﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bank
{
    public class Bank
    {
        //设置账户容量为100
        public static int size = 100;
        private CreditAccount[] CreditAccounts = new CreditAccount[size];

        //索引
        public CreditAccount this[int index]
        {
            get
            {
                return CreditAccounts[index];
            }
            set
            {
                CreditAccounts[index] = value;
            }
        }        

        //注销账户方法，销毁成功返回true，否则返回false
        public bool closeCreditAccount(int acc)
        {
            //遍历所有账户，寻找账户号匹配的账户对象销毁
            for(int i = 0;i < size;i ++)
            {
                if (CreditAccounts[i] == null)    
                    continue;
                if (CreditAccounts[i].getId() == acc)
                {
                    CreditAccounts[i] = null;
                    return true;
                }
            }
            return false;
        }

        //创建账户
        public int openCreditAccount(int pwd)
        {
            bool flag = true;    //标识随机生成的新账户号是否与已有账户号重复
            Random ra = new Random();
            int acc = ra.Next(10000000);   //随机生成账户号
            //遍历所有已存在账户
            while(true)
            {
                for (int i = 0; i < size; i++)
                {
                    if (CreditAccounts[i] != null)
                    {
                        if (CreditAccounts[i].getId() == acc)  //新生成的账户号与现有已开户账户号重复
                        {
                            acc = ra.Next(10000000);
                            flag = false;
                            break;
                        }
                    }
                }
                if (flag)   //若未重复，则跳出循环
                    break;
            }
            //遍历CreditAccounts，创建新的账户对象
            for (int i = 0; i < size; i++)
            {
                if (CreditAccounts[i] == null)
                {
                    CreditAccounts[i] = new CreditAccount(acc, 0, pwd, 0, 0, DateTime.Now.AddMonths(1));
                    break;
                }
            }
            return acc;
        }

        //查找账户对象，查找成功返回账户对象，否则返回null
        public CreditAccount findCreditAccount(int acc)
        {
            for (int i = 0; i < size; i++)
            {
                if (CreditAccounts[i] == null)
                    continue;
                if (CreditAccounts[i].getId() == acc)
                {
                    return CreditAccounts[i];
                }
            }
            return null;
        }
    }
}
